package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/***
 * 该类解析mapper.xml
 */

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    //解析mapper.xml
    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        //拿到usermapper.xml
        Document document = new SAXReader().read(inputStream);
        //拿到根标签
        Element rootElement = document.getRootElement();
        //拿到namespace标签
        String namespace = rootElement.attributeValue("namespace");
        //拿到select标签
        List<Element> list = rootElement.selectNodes("select");
        list.addAll(rootElement.selectNodes("insert"));
        list.addAll(rootElement.selectNodes("update"));
        list.addAll(rootElement.selectNodes("delete"));

        for (Element element : list) {
            //拿到id
            String id = element.attributeValue("id");
            //拿到参数类型
            String paramterType = element.attributeValue("paramterType");
            //拿到返回值类型
            String resultType = element.attributeValue("resultType");
            //拿到sql语句
            String sqlTest = element.getTextTrim();
            //放到mappedStatement中
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlTest);
            //定义statementId
            String key = namespace + "." + id;
            //存入configuration
            configuration.getMappedStatementMap().put(key, mappedStatement);


        }
    }

}
